package sax;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class Manager {

	private MySqlWorker worker = null;
	private ToXML toXML;
	private String pathXML;

	public Manager(String path) throws FileNotFoundException, IOException,
			SQLException {
		Properties dbProps = new Properties();
		dbProps.load(new FileReader(path + "db.properties"));
		String user = dbProps.getProperty("user");
		String passwd = dbProps.getProperty("password");
		String urlddress = dbProps.getProperty("url");
		pathXML = dbProps.getProperty("pathXML");
		String url = "jdbc:mysql://" + urlddress;
		worker = new MySqlWorker(url, user, passwd);
		toXML = new ToXML(pathXML);
	}

	public void processExportingToXML() throws SQLException, IOException {
		ResultSet rs = null;
		String info = null;
		rs = worker.returnAllFromTable("People");

		info = toXML.toXMLFirstTable(rs);
		toXML.toFile(info);
		rs = worker.returnAllFromTable("Trip");
		info = toXML.toXMLSecondTable(rs);
		toXML.toFile(info);
		rs = worker.returnAllFromTable("carShop");
		info = toXML.toXMLThirdTable(rs);
		toXML.toFile(info);
		toXML.doOnExit();
	}

	public void processImportToDB() throws IOException, SAXException,
			ParserConfigurationException {

		SAXHandler duper = new SAXHandler(worker);

		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser parser = spf.newSAXParser();
		XMLReader reader = parser.getXMLReader();
		reader.setContentHandler(duper);
		InputSource is = new InputSource(pathXML);
		reader.parse(is);
	}

	public void doOnExit() throws SQLException {
		worker.close();
		worker = null;
		toXML = null;
	}
}
